#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <magic.h>

#define BOLD_GRAY "\033[1;90m"
#define RED "\033[0;31m"
#define WHITE "\033[0;37m"
#define RESET "\033[0m"

int module_04_run(const char *filename) {
    char log_msg[1024];

    magic_t magic = magic_open(MAGIC_MIME_TYPE | MAGIC_ERROR | MAGIC_NO_CHECK_CDF);
    if (!magic) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library libmagic: " RED "File type not recognized: Error initializing libmagic" RESET);
        printf("%s\n", log_msg);
        return 1;
    }

    if (magic_load(magic, NULL) != 0) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library libmagic: " RED "File type not recognized: Error loading magic database: %s" RESET,
                 magic_error(magic));
        printf("%s\n", log_msg);
        magic_close(magic);
        return 1;
    }

    const char *mime = magic_file(magic, filename);
    if (!mime || strlen(mime) == 0 || strstr(mime, "\xFF") || strstr(mime, "\x00")) {
        mime = "text/plain";
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library libmagic: " RED "Invalid MIME, assuming text/plain" RESET);
        printf("%s\n", log_msg);
    }

    magic_setflags(magic, 0);
    const char *desc = magic_file(magic, filename);
    snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library libmagic: " WHITE "MIME: %s, Description: %s" RESET,
             mime, desc ? desc : "Unknown");
    printf("%s\n", log_msg);
    magic_close(magic);
    return 0;
}
